#! /usr/bin/python
import sys,os
import socket
import time

def httpclient():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((socket.gethostbyname("www.baidu.com"), 80))
    s.send("GET / HTTP/1.1\r\n\r\n")
    s.shutdown(1)
    buf = s.recv(1024)
    while  buf:
        sys.stdout.write(buf)
        buf = s.recv(1024)
    s.close()

#httpclient()

def bingfaclient():
    client = 20
    clients = []
    while client > 0:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        clients.append((client, s))
        client = client - 1;

    for clientno,s in clients:
        s.connect((socket.gethostname(), 8080))
    while 1:
        if len(clients) == 0:
            break
        for clientno, s in clients:
            try:
                s.send("GET / HTTP/1.1\r\n\r\n")
                #s.shutdown(1)
                buf = s.recv(1024)
                sys.stdout.write("client " + str(clientno) + ": \n" + buf)
            except socket.error:
                print "except happend:", socket.error()
                s.close(s)
                clients.remove((clientno, s))
        time.sleep(3)

bingfaclient()

print socket.gethostname()
print socket.gethostbyname("www.baidu.com")
print socket.gethostbyaddr("127.0.0.1")
print socket.getservbyname('http',"tcp")
print socket.getservbyname('pop3',"tcp")
print "smtp:", socket.getservbyname('smtp', "tcp")
print socket.getprotobyname('tcp')


print socket.getservbyport(23)

def pop3client():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((socket.gethostbyname("pop3.nfschina.com"), 110))
    s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
    responce = s.recv(1024)
    print ">> ", responce
    print(">> ")
    cmd = sys.stdin.readline()
    while responce and cmd:
        try:
            s.send(cmd)
            responce = s.recv(4096)
            print ">> ", responce
            print(">> ")
            cmd = sys.stdin.readline()
        except:
            print "connection down"
            break

#pop3client()
